/**
 * 易驰护运 - Mine
 * http://menger.me
 * @大梦
 */

'use strict';

import React from 'react';
import {StyleSheet, Text, ScrollView, TouchableOpacity, View} from 'react-native';
import {
    Badge,
    TagItem,
    ListRow,
    ListHeaderLoading,
} from '../../components'
import {MineStyle} from '../../style'
import {inject, observer} from 'mobx-react'
import {request} from 'react-native-permissions';

@inject('loginStore')
@observer
export default class Mine extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isRefreshing: false,
            orderNavArray: [
                {title: '待审核', icon: Images.icon_nav_order1, component: 'Order', badge: 0, params: {initialPage: 1}},
                {title: '待开始', icon: Images.icon_nav_order2, component: 'Order', badge: 0, params: {initialPage: 2}},
                {title: '运输中', icon: Images.icon_nav_order3, component: 'Order', badge: 0, params: {initialPage: 3}},
                {title: '待收款', icon: Images.icon_nav_order4, component: 'Order', badge: 0, params: {initialPage: 4}},
                {title: '已完成', icon: Images.icon_nav_order5, component: 'Order', badge: 0, params: {initialPage: 5}},
            ],
            navArray: [
                {title: '会员中心', icon: Images.icon_user_vip, component: 'Vip'},
                {title: '车辆管理', icon: Images.icon_user_car, component: 'ManageCar'},
                {title: '我的钱包', icon: Images.icon_user_wallet, component: 'Wallet'},
                {title: '支付密码', icon: Images.icon_user_wallet, component: 'PayPassword'},
                {
                    title: '专属顾问',
                    icon: Images.icon_user_adviser,
                    component: 'WebPage',
                    margin: 10,
                    params: {uri: ServicesApi.PERSONAL_ADVISER}
                },
                {
                    title: '联系客服',
                    icon: Images.icon_user_customer,
                    component: 'WebPage',
                    params: {uri: ServicesApi.CUSTOMER_SERVICE}
                },
                {
                    title: '公司简介',
                    icon: Images.icon_user_profile,
                    component: 'WebPage',
                    params: {uri: ServicesApi.COMPANY_PROFILE}
                },
                {title: '退出登录', icon: Images.icon_user_setting, component: 'Setting'},
            ],
            dataSource: [],
        }
        // 进入页面后刷新用户信息
        this.props.navigation.addListener('willFocus', this.componentWillFocus);
    }

    // 增加CallBack的跳转方法
    _onPressToNavigate = (pageTitle, component, params) => {
        let {loginStore} = this.props;
        let {userInfo} = loginStore;
        if (component == 'ManageCar') {
            if (userInfo.is_pass == 1) {
                RouterHelper.navigate(pageTitle, component, {
                    ...params,
                    onCallBack: () => loginStore.getLatestUserInfo(),
                });
            } else {
                let params = {
                    title: '温馨提醒',
                    detail: '您需要先通过认证才能编辑车辆哦',
                    actions: [
                        {title: '再看看'},
                        {
                            title: '公司认证',
                            titleStyle: {color: Predefine.themeColor},
                            onPress: () => RouterHelper.navigate('', 'Approve')
                        },
                    ]
                };
                AlertManager.show(params);
            }
        } else if (component == 'Setting') {
            this._onPressLogout()
        } else {
            RouterHelper.navigate(pageTitle, component, {
                ...params,
                onCallBack: () => loginStore.getLatestUserInfo(),
            });
        }
    };

    componentWillFocus = () => {
        this.initialRequestDataSources();
    }

    componentDidMount() {
        this.requestData();
        this.initialRequestDataSources();
        let {loginStore} = this.props;
        let {userInfo} = loginStore;
        userInfo.id && this.checkCar();
    }

    checkCar = async () => {
        let {loginStore} = this.props;
        let {userInfo} = loginStore;
        let url = ServicesApi.INDEX_CHECK_VALIDITY;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            if (userInfo.is_pass == 1) {
                let data = {
                    asd: '1',
                    ids: '20',
                           
                };
                let params = {
                    title: '温馨提醒',
                    detail: '您有证件过期的车辆哦。',
                    actions: [
                        {title: '再看看'},
                        {
                            title: '车辆管理',
                            titleStyle: {color: Predefine.themeColor},
                            onPress: () => RouterHelper.navigate('', 'ManageCar')
                        },
                    ]
                };
                AlertManager.show(params);
            } else {
                let params = {
                    title: '温馨提醒',
                    detail: '您有证件过期的车辆，您需要先通过认证才能编辑车辆哦',
                    actions: [
                        {title: '再看看'},
                        {
                            title: '公司认证',
                            titleStyle: {color: Predefine.themeColor},
                            onPress: () => RouterHelper.navigate('', 'Approve')
                        },
                    ]
                };
                AlertManager.show(params);
            }
        }
    }

    requestData = async () => {
        let url = ServicesApi.PERSONAL_CENTER_ORDER_STATUS_NUM;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                orderNavArray: [
                    {
                        title: '待审核',
                        icon: Images.icon_nav_order1,
                        component: 'Order',
                        badge: result.data.is_pass,
                        params: {initialPage: 1}
                    },
                    {
                        title: '待开始',
                        icon: Images.icon_nav_order2,
                        component: 'Order',
                        badge: result.data.is_start,
                        params: {initialPage: 2}
                    },
                    {
                        title: '运输状态',
                        icon: Images.icon_nav_order3,
                        component: 'Order',
                        badge: result.data.is_transport,
                        params: {initialPage: 3}
                    },
                    {
                        title: '待收款',
                        icon: Images.icon_nav_order4,
                        component: 'Order',
                        badge: result.data.is_income,
                        params: {initialPage: 4}
                    },
                    {
                        title: '已完成',
                        icon: Images.icon_nav_order5,
                        component: 'Order',
                        badge: result.data.is_finish,
                        params: {initialPage: 5}
                    },
                ],
            });
        }
    }

    _onRefresh = async () => {
        this.setState({isRefreshing: true});
        this.requestData();
        this.initialRequestDataSources();
        setTimeout(() => this.setState({
            isRefreshing: false
        }), 500);
    };

    // 初始化用户信息
    initialRequestDataSources = async () => {
        let {loginStore} = this.props;
        let {getLatestUserInfo} = loginStore;
        getLatestUserInfo && getLatestUserInfo();
    };

    // 退出登录
    _onPressLogout = () => {
        let {loginStore} = this.props;
        let params = {
            title: '温馨提醒',
            detail: '您确定要退出吗？',
            actions: [
                {title: '取消'},
                {
                    title: '确认',
                    titleStyle: {color: Predefine.themeColor},
                    onPress: () => loginStore.doLogout()
                },
            ]
        };
        AlertManager.show(params);
    };

    _renderOrderNavigationContent = (navArray) => {
        if (navArray.length < 1) return null;
        let content = navArray.map((item, index) => {
            return (
                <Button
                    key={index}
                    style={[Predefine.CCC, styles.orderNavBtnItem]}
                    onPress={() => this._onPressToNavigate('', item.component, item.params)}
                >
                    <ImageView
                        source={item.icon}
                        style={styles.orderNavBtnItemIcon}
                    />
                    <Text style={styles.orderNavBtnItemTitle}>{item.title}</Text>
                    <Badge count={item.badge} style={styles.orderNavBtnItemBadge}/>
                </Button>
            );
        });
        return content;
    }

    _renderNavigationContent = (navArray) => {
        if (navArray.length < 1) return null;
        let content = navArray.map((item, index) => {
            return (
                <ListRow
                    key={index}
                    title={item.title}
                    icon={item.icon}
                    style={[styles.navItemStyle, item.margin && Predefine.MB10]}
                    iconStyle={styles.navItemIconStyle}
                    titleStyle={styles.navItemTitleStyle}
                    bottomSeparator={(item.margin || index == navArray.length - 1) ? 'none' : 'indent'}
                    onPress={() => this._onPressToNavigate(item.title, item.component, item.params)}
                />
            );
        });
        return content;
    };
    // 退出登录
    _onPressLogout = () => {
        let {loginStore} = this.props;
        let params = {
            title: '温馨提醒',
            detail: '您确定要退出吗？',
            actions: [
                {title: '取消'},
                {
                    title: '确认',
                    titleStyle: {color: Predefine.themeColor},
                    onPress: () => {
                        loginStore.doLogout();
                        RouterHelper.reset('', 'Tab');
                    }
                },
            ]
        };
        AlertManager.show(params);
    };

    render() {
        let pageTitle = '个人中心';
        let {navArray, orderNavArray} = this.state;
        let {loginStore} = this.props;
        let {userInfo, getJSDataSources} = loginStore;
        console.log('getJSDataSources(userInfo)------------->', getJSDataSources(userInfo))
        let isPassText = '';
        if (userInfo.is_pass == -2) {
            isPassText = '去认证 >'
        } else if (userInfo.is_pass == -1) {
            isPassText = '审核中 >'
        } else if (userInfo.is_pass == 0) {
            isPassText = '未通过 重新提交 >'
        } else if (userInfo.is_pass == 1) {
            isPassText = '已通过 >'
        }
        return (
            <PageContainer style={styles.container}>
                <NavigationBar 
                    title={pageTitle} 
                    renderLeftAction={null}
                    renderRightAction={[{
                        title: <Text style={styles.navigationBarBtn}>设置</Text>,
                        onPress: () => RouterHelper.navigate('', 'Setting', {})
                    }]}
                />
                <ScrollView style={styles.content} refreshControl={<ListHeaderLoading onRefresh={this._onRefresh} refreshing={this.state.isRefreshing}/>}>
                    <TouchableOpacity
                        style={[Predefine.RCB, styles.userInfoView]}
                        onPress={() => userInfo.id && RouterHelper.navigate('', 'ChangeUserInfo', {
                            onRefresh: () => this._onRefresh()
                        })}
                    >
                        {
                            userInfo.id
                                ?
                                <View style={[Predefine.RCB]}>
                                    <View style={[Predefine.CCC, styles.userAvatarView]}>
                                        <ImageView
                                            resizeMode={'cover'}
                                            style={styles.userAvatarStyle}
                                            source={userInfo.avatar ? {uri: userInfo.avatar} : Images.img_nopicture1}
                                        />
                                        <TagItem
                                            style={styles.userLevelStyle}
                                            titleStyle={styles.userLevelTitleStyle}
                                            title={userInfo.level_name || '普通会员'}
                                        />
                                    </View>
                                    <View style={[Predefine.RCB, styles.userInfoDetailView]}>
                                        <View style={[Predefine.CAS, styles.userInfoDetailLeftView]}>
                                            <Text style={styles.userNameStyle}>{userInfo.nickname || '用户昵称'}</Text>
                                            <TouchableOpacity style={[Predefine.RCS, styles.companyInfo]}>
                                                <Text style={styles.companyNameStyle}>公司：</Text>
                                                <Button
                                                    title={isPassText}
                                                    style={styles.userInfoBtnStyle}
                                                    titleStyle={styles.userInfoBtnTitleStyle}
                                                    onPress={() => RouterHelper.navigate('', 'Approve')}
                                                />
                                            </TouchableOpacity>
                                        </View>
                                        <ImageView
                                            source={Images.icon_arrow_right}
                                            style={styles.userInfoArrowIconStyle}
                                        />
                                    </View>
                                </View>
                                :
                                <View style={{flex: 1, paddingHorizontal: 100}}>
                                    <Button
                                        style={{backgroundColor: '#fff'}}
                                        title={'去登陆'}
                                        titleStyle={{color: '#2ED1DC'}}
                                        resizeMode={'cover'}
                                        backgroundImage={Images.img_btn_bg1}
                                        onPress={() => RouterHelper.navigate('', 'Login')}
                                    />
                                </View>
                        }
                    </TouchableOpacity>
                    {
                        userInfo.id &&
                        <View style={[styles.orderNavContentStyle]}>
                            <ListRow
                                title={'我的订单'}
                                detail={'查看全部订单'}
                                bottomSeparator={'none'}
                                style={styles.orderNavContentTitleView}
                                titleStyle={styles.orderNavContentTitleStyle}
                                contentStyle={styles.orderNavContentTitleConStyle}
                                detailStyle={styles.orderNavContentTitleDetailStyle}
                                onPress={() => RouterHelper.navigate('', 'Order')}
                            />
                            <View style={[Predefine.RCB, styles.orderNavContentCon]}>
                                {this._renderOrderNavigationContent(orderNavArray)}
                            </View>
                        </View>
                    }
                    {
                        userInfo.id
                            ? <View style={[Predefine.MT10, styles.navContentStyle]}>
                                {this._renderNavigationContent(navArray)}
                            </View>
                            : <View style={{
                                marginTop: 15,
                                marginHorizontal: 15,
                                padding: 10,
                                borderRadius: 10,
                                backgroundColor: '#fff',
                            }}>
                                <Text style={{color: '#333', fontSize: 13}}>登录使用更多功能</Text>
                            </View>
                    }
                </ScrollView>
            </PageContainer>
        );
    }
}

const styles = StyleSheet.create({
    ...MineStyle,
    navigationBarBtn: {
        color: '#fff',
        fontSize: 14,
    },
});
